import {ping} from './ping';
import {gval} from '../configs/global';
const packageJSON = require('../../env.json');
const ProxyListKey = 'xlListKey';


export async function getBestProxyApiUrl() {
    let item = await getBestProxyItem().catch(logger);
    return item.url;
}

export async function getBestProxyItem(isRefresh = false) {
    if (isRefresh || !gval.bestProxyItem) {
        let lists = await getProxyList().catch(logger);
        let item = {};
        for (let val of lists) {
            if (typeof item.delta === 'undefined' || val.delta < item.delta) {
                item = val;
            }
        }

        gval.bestProxyItem = item;
    }
    return gval.bestProxyItem;
}


export async function getProxyList() {
    // let lists = await storage.load({key:ProxyListKey}).catch(logger);
    // if (!lists) {
    //     lists = await setProxyList().catch(logger);
    // }
    // if (lists && !Array.isArray(lists)) {
    //     lists = Object.values(lists);
    // }
    // return lists || [];
}

export async function setProxyList(apiUrl) {
    // const res = await axios.get((apiUrl||'') + api.getProxyList).catch(e => {
    //     logger('代理请求错误', e);
    // });
    // let lists = [];
    // if (res && res.data) {
    //     let data = res.data;
    //     if (!data || (Array.isArray(data) && !data.length)) {
    //         data = [packageJSON.defaultApiUrl];
    //     }
    //     let lists = await getProxyPingList(data).catch(logger);
    //     if (lists && !Array.isArray(lists)) {
    //         lists = Object.values(lists);
    //     }
    //     storage.save({key:ProxyListKey, data:lists}).catch(logger);
    // }

    // return lists;
}

async function getProxyPingList(data) {
    let promises = [];
    data.forEach(val => {
        promises.push(ping(val, 8));
    });
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(res => {
            let lists = {};
            res.forEach((delta, i) => {
                if (typeof data[i] === 'undefined') {
                    return;
                }
                lists[i] = {
                    index: i,
                    url: data[i],
                    delta: delta,
                };
            });
            resolve(lists);
        }).catch(reject);
    });
}
